<!-- 高德地图 -->
<template>
  <div class="amap-page-container">

    <div>
      <el-input class="tipinput" v-model="address" placeholder="请输入地址" />
      <ul class="ulList" v-if="tips.length > 0">
        <li v-for="(item, index) in tips" :key="index">
          <div class="liDiv" @click="change(item)">
            <span>{{ item.name }}</span>
            <span class="liSpan">{{ item.district }}</span>
          </div>
        </li>
      </ul>

      <el-button type="primary" icon="el-icon-search" @click="getLocationByInput">搜索</el-button>
    </div>

    <el-amap
      :vid="mapId"
      :center="center"
      :amap-manager="amapManager"
      :zoom="zoom"
      :events="events"
      style="height: 400px; margin-top: 20px;"
    >
      <el-amap-marker ref="marker" vid="component-marker" :position="center"></el-amap-marker>
    </el-amap>

    <div class="foot-but">
      <el-button type="primary" @click="submit">确定</el-button>
    </div>

  </div>
</template>

<script>
import { AMapManager } from 'vue-amap';
const amapManager = new AMapManager();

export default {
  name: 'GDMap',
  props: {
    // 地图容器节点的ID
    mapId: {
      type: String,
      default: 'amapDemo'
    }
  },
  data () {
    return {
      // 初始值默认为天安门
      adcode: '110101',
      center: [116.397451, 39.909187],
      address: '北京市东城区东华门街道天安门',
      zoom: 13,
      amapManager,
      geocoder: null, // 地理编码对象
      autoComplete: null, // 输入提示对象
      tips: [],
      events: {
        click: (e) => {
          this.center = [e.lnglat.lng, e.lnglat.lat];
          this.getAddressByLocation();
        }
      }
    };
  },
  mounted() {
    this.initLocation();
  },
  methods: {
    // 初始化定位
    initLocation() {
      let that = this;
      // IP定位获取当前城市信息
      AMap.plugin('AMap.Geolocation', function() {
        var geolocation = new AMap.Geolocation({
          // 是否使用高精度定位，默认：true
          enableHighAccuracy: false,
          // 设置定位超时时间，默认：无穷大
          timeout: 5000,
          // 定位按钮的停靠位置的偏移量
          offset: [10, 20],
          //  定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
          zoomToAccuracy: true
        })
        geolocation.getCityInfo(function(status, result) {
          // console.log('通过定位拿到的地址', result);
          if(status == 'complete' && result.info == 'SUCCESS') {
            that.adcode = result.adcode;
            that.center = result.center;
            that.getAddressByLocation();
          }
        })
      })
    },
    // 逆向地理编码：地理坐标（经纬度） -> 地址描述信息
    getAddressByLocation() {
      let that = this;
      if(!that.geocoder) {
        AMap.plugin('AMap.Geocoder', () => {
          let GeocoderOptions = {
            city: that.adcode || '全国'
          };
          that.geocoder = new AMap.Geocoder(GeocoderOptions);
        })
      }
      that.geocoder.getAddress(that.center, (status, result) => {
        // console.log('通过经纬度拿到的地址', result);
        if (status === 'complete' && result.info === 'OK') {
          that.adcode = result.regeocode.addressComponent.adcode;
          that.address = result.regeocode.formattedAddress;
        } else {
          that.$modal.msgError("无法获取地址，请重新选择");
        }
      })
    },
    // 输入提示
    getLocationByInput() {
      let that = this;
      if(!that.autoComplete) {
        AMap.plugin('AMap.Autocomplete', () => {
          let autoOptions = {
            city: that.adcode || '全国'
          };
          that.autoComplete = new AMap.Autocomplete(autoOptions);
        });
      }
      if(that.address) {
        that.loading = true;
        that.autoComplete.search(that.address, function(status, result) {
          that.loading = false;
          // console.warn(status)
          // console.warn(result)
          if (status == 'complete' && result.info == 'OK') {
            that.tips = result.tips;
          } else {
            if(result == 'USER_DAILY_QUERY_OVER_LIMIT') {
              that.$modal.msgError("搜索调用量超过限制，请点击地图选择");
            } else {
              that.$modal.msgError("无法搜索地址，请点击地图选择");
            }
          }
        })
      } else {
        that.$modal.msgError("请输入地址");
      }
    },
    // 选中
    change(tip) {
      this.adcode = tip.adcode;
      this.center = [tip.location.lng, tip.location.lat];
      this.getAddressByLocation();
    },
    // 回调
    submit() {
      this.$emit("getAddress", this.adcode, this.address, this.center[0], this.center[1]);
      this.tips = [];
    }
  }
};
</script>

<style>
  .tipinput {
    width: 40%;
    margin-right: 10px;
    position: relative;
  }
  .ulList {
    position: absolute;
    z-index: 9999;
    list-style: none;
    padding: 10px;
    margin: 0;
    border: 1px solid #d1d1d1;
    background: rgba(255,255,255,0.9);
  }
  .liDiv {
    white-space: nowrap;
    font-size: 14px;
    cursor: pointer;
    padding: 4px;
  }
  .liDiv:hover{
    background: #b3d8ff;
  }
  .liSpan {
    font-size: 13px;
    color: #c1c1c1;
    padding-left: 4px;
  }
  .foot-but {
    text-align: center;
    margin-top: 20px;
  }
  .amap-sug-result {
    z-index: 99999;
  }
</style>
